package utils

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"encoding/base64"
	"interview/pkg/global"
)

func PKCS7Padding(ciphertext []byte, blocksize int) []byte {
	padding := blocksize - len(ciphertext)%blocksize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, padtext...)
}

func PKCS7UnPadding(origData []byte) []byte {
	length := len(origData)
	unpadding := int(origData[length-1])
	return origData[:(length - unpadding)]
}

func AesEncrypt(data string) string {
	key := []byte(global.AssetsKey)
	origStr := []byte(data)

	block, _ := aes.NewCipher(key)
	blockSize := block.BlockSize()
	origStr = PKCS7Padding(origStr, blockSize)

	blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
	cryted := make([]byte, len(origStr))
	blockMode.CryptBlocks(cryted, origStr)

	return base64.StdEncoding.EncodeToString(cryted)

}

func AesDecrypt(cryted string) string {
	key := []byte(global.AssetsKey)
	crytedByte, _ := base64.StdEncoding.DecodeString(cryted)

	block, _ := aes.NewCipher(key)
	blockSize := block.BlockSize()
	blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])

	orig := make([]byte, len(crytedByte))
	blockMode.CryptBlocks(orig, crytedByte)

	orig = PKCS7UnPadding(orig)
	return string(orig)
}
